<?php

namespace stlswm\AliOpenPlatform\DingRobot;

use Exception;

/**
 * Class DingRobot
 * 阿里DingDing机器人
 *
 * @package AliOpenPlatform\DingRobot
 */
class DingRobot
{
    private static $url = 'https://oapi.dingtalk.com/robot/send?access_token=';
    private $token = '';
    private $tokenAlias = [];

    /**
     * @param string $json
     * @param int    $timeout
     *
     * @return bool|string
     * @throws Exception
     */
    private function net(string $json, $timeout = 2)
    {
        $headers = [
            'Content-Type: application/json',
        ];
        if(!$this->token){
            throw new Exception('token not set');
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, self::$url . $this->token);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }

    /**
     * @param string $token
     *
     * @return DingRobot
     * @author wangmin
     */
    public function setDefaultToken(string $token): DingRobot
    {
        $this->tokenAlias['default'] = $token;
        return $this;
    }

    /**
     * @param string $alias
     * @param string $token
     *
     * @return DingRobot
     */
    public function setTokenAlias(string $alias, string $token): DingRobot
    {
        $this->tokenAlias[$alias] = $token;
        return $this;
    }

    /**
     * @param string $alias
     *
     * @return DingRobot
     * @throws Exception
     */
    public function useToken(string $alias = 'default'): DingRobot{
        if(isset($this->tokenAlias[$alias])){
            $this->token = $this->tokenAlias[$alias];
            return $this;
        }
        throw new Exception('no token named:'.$alias);
    }

    /**
     * @param string $msg
     * @param array  $atMobiles
     * @param bool   $isAtAll
     *
     * @return bool
     * @throws Exception
     */
    public function sendText(string $msg, array $atMobiles = [], bool $isAtAll = FALSE): bool
    {
        $text = [
            "msgtype" => "text",
            "text"    => [
                "content" => $msg,
            ],
            "at"      => [
                "atMobiles" => $atMobiles,
                "isAtAll"   => $isAtAll,
            ],
        ];
        $result = self::net(json_encode($text));
        if (!$result) {
            return FALSE;
        }
        $result = json_decode($result);
        if (!$result) {
            return FALSE;
        }
        if (isset($result->errcode) && $result->errcode == 0) {
            return TRUE;
        }
        return FALSE;
    }
}